package com.isoft.c2team3service2.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.isoft.c2team3service2.entity.PostArtistTag;
import com.isoft.c2team3service2.mapper.PostArtistTagMapper;
import com.isoft.c2team3service2.service.PostArtistTagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class PostArtistTagServiceImpl extends ServiceImpl<PostArtistTagMapper, PostArtistTag> implements PostArtistTagService {

    @Autowired
    private PostArtistTagMapper postArtistTagMapper;

    @Override
    @Transactional
    public void addArtistTagsToPost(Integer postId, List<Integer> artistIds) {
        if (postId == null || artistIds == null || artistIds.isEmpty()) {
            return;
        }
        // 1. 先删除该帖子已有的艺人标签（避免重复）
        postArtistTagMapper.deleteByPostId(postId);
        // 2. 批量新增标签
        List<PostArtistTag> tags = artistIds.stream()
                .map(artistId -> {
                    PostArtistTag tag = new PostArtistTag();
                    tag.setPostId(postId);
                    tag.setArtistId(artistId);
                    return tag;
                })
                .collect(Collectors.toList());
        saveBatch(tags);
    }

    @Override
    public List<Integer> getPostIdsByArtistNameLike(String artistName) {
        if (artistName == null || artistName.trim().isEmpty()) {
            return List.of();
        }
        return postArtistTagMapper.selectPostIdsByArtistNameLike(artistName.trim());
    }

    @Override
    @Transactional
    public void deleteTagsByPostId(Integer postId) {
        postArtistTagMapper.deleteByPostId(postId);
    }
}